from django.db import models
from django.contrib.contenttypes.models import ContentType

# Create your models here.
class OnModelChange(models.Model):
    content_type = models.ForeignKey(ContentType)
    absolute = models.BooleanField(name='Use absolute url', default=True)
    delete = models.BooleanField(help_text='Delete cache on change', default=True)
    publish = models.BooleanField(help_text='Publish cache on change', default=False)
    
    def get_urls(self, obj):
        ret = [url['url'] for url in self.staticurl_set.values('url')]
        if self.absolute:
            ret.extend(ModelUrl(attribute='get_absolute_url').get_urls(obj))
        for url in self.modelurl_set.all():
            ret.extend(url.get_urls(obj))
        return ret
    
    def __unicode__(self):
        return self.content_type.name
    
class ModelUrl(models.Model):
    model_change = models.ForeignKey(OnModelChange)
    attribute = models.CharField(max_length=255, help_text='The attribute of the model that gives back url(s)')
    
    def get_urls(self, obj):
        if hasattr(obj, self.attribute):
            try:
                attr = getattr(obj, self.attribute)
            except:
                return []
            if callable(attr):
                try:
                    attr = attr()
                except:
                    return []
            if isinstance(attr, (list, tuple)):
                return attr
            return [attr]
        return []

    def __unicode__(self):
        return self.attribute

class StaticUrl(models.Model):
    model_change = models.ForeignKey(OnModelChange)
    url = models.CharField(max_length=255)
    
    def __unicode__(self):
        return self.url
    
